package com.uchengwang.ui.base_ui.basefm;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.cycle.ui.LoadCycleWebHtmlActivity;
import com.uchengwang.ui.cm_ui.rychat.adapter.ConversationListAdapterEx;
import com.uchengwang.ui.cm_ui.umsg.adapter.MsgTopAdapter;
import com.uchengwang.ui.cm_ui.umsg.ui.ClubMainActivity;
import com.uchengwang.ui.cm_ui.uu.bean.XiangliaoBean;
import com.uchengwang.ui.cm_ui.uu.http.XiangliaoManager;
import com.uchengwang.ui.cm_ui.uu.ui.FindActivity;
import com.uchengwang.ui.cm_ui.uu.ui.QRScanActivity;
import com.uchengwang.ui.cm_ui.uu.ui.XiangliaoActivity;
import com.uchengwang.ui.cm_ui.uu.ui.XiangliaoChooseMoodActivity;
import com.uchengwang.ui.utils.ToastManager;
import com.uchengwang.ui.utils.UCommonUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import io.rong.imkit.RongContext;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;


/**
 * Created by U城网 on 2017/10/11.
 */

public class FragmentUU extends BaseFragment implements View.OnClickListener{
    private View view;
    private ActivityTitleBar titleBar;
    public static boolean isSendMsg = false;
    private RelativeLayout msg_fm;
    private Conversation.ConversationType[] mConversationsTypes = null;
    private boolean isHide;//是否隐藏titleBar
    private TextView msg_no_login;
    private GridView gridView;
    private MsgTopAdapter adapter;
    private long reFreshTime;//刷新时间
    private LinearLayout msg_search;
    /**
     * 会话列表的fragment
     */
    private ConversationListFragment mConversationListFragment = null;
    private RelativeLayout chat_main_rl, room_main_rl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setLayoutId(R.layout.fragment_msg);
        view = super.onCreateView(inflater, container, savedInstanceState);
        initView(view);
        return view;
    }

    private void initView (View view){
        titleBar = (ActivityTitleBar) view.findViewById(R.id.fmMsg_titleBar);
        titleBar.setTitle("消息", R.color.white);
        titleBar.getTitleBar_bg().setBackground(null);
        if (isHide){
            titleBar.setVisibility(View.GONE);
        }
        titleBar.setImageLeft(R.drawable.icon_msg_saoyisao, 96, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(FragmentUU.this.getContext(), QRScanActivity.class));
//                ((MainActivity)FragmentUU.this.getActivity()).openDrawerLayout();
            }
        });

        msg_search = view.findViewById(R.id.msg_search);
        msg_search.setOnClickListener(this);

        chat_main_rl = view.findViewById(R.id.chat_main_rl);
        chat_main_rl.setOnClickListener(this);

        room_main_rl = view.findViewById(R.id.room_main_rl);
        room_main_rl.setOnClickListener(this);

//        final List<ChooseItemBean> chooseItemBeans = new ArrayList<>();
//
//        chooseItemBeans.add(new ChooseItemBean("扫一扫", R.drawable.icon_msg_saoyisao, 0, R.color.ustudy_no_choose));
//        chooseItemBeans.add(new ChooseItemBean("找同学", R.drawable.icon_msg_find_person, 0, R.color.ustudy_no_choose));
        titleBar.setImageRight(R.drawable.icon_msg_left, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UCommonUtil.getUtil().isNeedLogin(FragmentUU.this.getActivity(), false)){
                    return;
                }
                startActivity(new Intent(FragmentUU.this.getContext(), FindActivity.class));



//                PopupUtils.getUtils().rgihtMoreWithIcon(FragmentUU.this.getContext(), titleBar, chooseItemBeans, R.drawable.shape_item_bg, new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                        PopupUtils.getUtils().dismiss();
//                        Intent intent = null;
//                        switch (i){
//                            case 0://扫一扫
//                                intent = new Intent(FragmentUU.this.getContext(), QRScanActivity.class);
//
//
//                                break;
//                            case 1://找人
//                                intent = new Intent(FragmentUU.this.getContext(), AddFriendActivity.class);
//                                intent.putExtra(BaseConfig.USER_ROLE, BaseConfig.STUDENT_ROLE);
//                                intent.putExtra(BaseConfig.TYPE, 2);
//                                break;
////                            case 2://找社团
////                                intent = new Intent(FragmentUU.this.getContext(), AddFriendActivity.class);
////                                intent.putExtra(BaseConfig.USER_ROLE, BaseConfig.CLUB_ROLE);
////                                intent.putExtra(BaseConfig.TYPE, 3);
////                                break;
//                        }
//                        if (intent != null){
//                            startActivity(intent);
//                        }
//                    }
//                });

            }
        });

//        gridView = view.findViewById(R.id.fmMsg_rv);
        msg_fm = view.findViewById(R.id.msg_fm);


        msg_no_login = view.findViewById(R.id.msg_no_login);//未登录
        msg_no_login.setOnClickListener(this);

//        List<MsgTopBean> list = new ArrayList<>();
//        if (UChengApplication.userRole == BaseConfig.CLUB_ROLE){
//            list.add(new MsgTopBean("找同学", R.drawable.image_find_friend_no));
//            list.add(new MsgTopBean("找社团", R.drawable.image_find_club_no));
//            list.add(new MsgTopBean("找赞助", R.drawable.image_find_club_no));
//        }else {
//            list.add(new MsgTopBean("享聊", R.drawable.image_want_chat));
//            list.add(new MsgTopBean("找同学", R.drawable.image_find_friend_no));
//            list.add(new MsgTopBean("找社团", R.drawable.image_find_club_no));
//        }

//        adapter = new MsgTopAdapter(getContext(),list);
//        gridView.setAdapter(adapter);


        refresh();

        if (UCommonUtil.getUtil().isLogin()){
            initData(false);
        }else {
            msg_fm.setVisibility(View.GONE);
            msg_no_login.setVisibility(View.VISIBLE);
        }


    }

    public void setTitleBarHide(boolean isHide){
        this.isHide = isHide;
    }

    public void initData(boolean isRefresh){
        Fragment conversationList = initConversationList(isRefresh);
        getChildFragmentManager().beginTransaction().replace(R.id.msg_fm, conversationList).commit();
    }

    private Fragment initConversationList(boolean isRefresh) {
        if (mConversationListFragment == null || isRefresh) {
            ConversationListFragment listFragment = new ConversationListFragment();

            listFragment.setAdapter(new ConversationListAdapterEx(RongContext.getInstance()));
            Uri uri = Uri.parse("rong://" + getContext().getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationlist")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                    .build();
            mConversationsTypes = new Conversation.ConversationType[]{Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP};

            listFragment.setUri(uri);
            mConversationListFragment = listFragment;
            return listFragment;
        } else {
            return mConversationListFragment;
        }
    }

    /**
     * 取消左上角的红点, 粉丝 好友 关注等
     * @param data 当data为"取消"时, 操作
     * */
//    public void onEvent(String data) {
//        if (!TextUtils.isEmpty(data) && data.equals(BaseConfig.EVENT_CANCEL)){
//            titleBar.setLeftMsg(0);
//            ((MainActivity)FragmentUU.this.getActivity()).hideDot(1);
//        }
//    }

    /**
     *刷新数据
     * */
    public void refresh() {

    }

    /**
     * 获取网络数据 新粉丝数量
     * */
//    public void refreshNet(){
//        HttpUserManager.getManager().getMyFans(getActivity(), false, new OnResultListener() {
//            @Override
//            public void onResult(int stutas, String msg, int total, String data) {
//                if (total >0 ){
//                    setMyFans(total);
//                    ((MainActivity)FragmentUU.this.getActivity()).refreshFans(1, total);
//                    ((MainActivity)FragmentUU.this.getActivity()).showDot(1);
//                }
//            }
//        });
//    }

    /**
     * 更新我的新粉丝数
     * */
//    public void setMyFans(int fansNum){
//        titleBar.setLeftMsg(fansNum);
//    }


    @Override
    public void onResume() {
        super.onResume();
        int msgNum = 0;
        if (getActivity() instanceof MainActivity){
            msgNum = ((MainActivity)this.getActivity()).getNoReadMsg(2);
        }else if (getActivity() instanceof ClubMainActivity){
            msgNum = ((ClubMainActivity)this.getActivity()).getNoReadMsg(2);
        }

        if (isSendMsg || msgNum >0) {
            refresh();
        }
        if (UCommonUtil.getUtil().isLogin() && (System.currentTimeMillis()- reFreshTime)/1000/60 >5){
//            refreshNet();
            reFreshTime = System.currentTimeMillis();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isSendMsg = false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
//            case R.id.fmMsg_notify://系统通知
//                if (UCommonUtil.getUtil().isNeedLogin(getActivity(), true)){
//                    return;
//                }
//                ChatHttpManager.getManager().getMyChatInfo(getActivity(), 1, new OnHttpResultSingleListener<WantChatBean>() {
//                    @Override
//                    public void onResult(int status, String msg, WantChatBean wantChatBean) {
//                        Intent intent = null;
//                        if (wantChatBean != null){
//                            intent = new Intent(getContext(), WantFindPersonsActivity.class);
//                            intent.putExtra(BaseConfig.BEAN, wantChatBean);
//
//                        }else {
//                            intent = new Intent(getContext(), WantChatEditorImgActivity.class);
//                            intent.putExtra(BaseConfig.TYPE, 0);
//                        }
//                        if (intent != null){
//                            startActivity(intent);
//                        }
//                    }
//                });
//                break;
            case R.id.msg_search:
//                Intent intent = new Intent(getContext(), LoadWebHtmlFillActivity.class);
//                intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/search");
//                startActivity(intent);
                Intent intent = new Intent(getContext(), LoadCycleWebHtmlActivity.class);
                intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/search");
                intent.putExtra(BaseConfig.IS_FULL, true);
                startActivity(intent);
                break;
            case R.id.msg_no_login:
                if (UCommonUtil.getUtil().isNeedLogin(this.getActivity(), false)){
                    return;
                }
                break;

            case R.id.chat_main_rl:
                //享聊
                XiangliaoManager.getManager().chatCheck(getActivity(), new OnResultListener() {
                    @Override
                    public void onResult(int stutas, String msg, int total, String data) {
                        if (stutas ==0){
                            //可以进入享聊
                            List<XiangliaoBean> beanList = LiteOrmDBUtil.getLiteOrm(FragmentUU.this.getContext()).getQueryByWhere(XiangliaoBean.class, "uid", String.valueOf(UCommonUtil.getUtil().getId()));
                            XiangliaoBean xiangliaoBean = null;
                            if (beanList != null && beanList.size() >0){
                                xiangliaoBean = beanList.get(0);
                            }

                            Intent in = null;
                            if (xiangliaoBean == null || ((System.currentTimeMillis()-xiangliaoBean.getCreateTime()) >12*60*60*1000)){
                                in = new Intent(FragmentUU.this.getContext(), XiangliaoChooseMoodActivity.class);
                            }else {
                                in = new Intent(FragmentUU.this.getContext(), XiangliaoActivity.class);
                            }
                            FragmentUU.this.getContext().startActivity(in);

                        }else {
                            ToastManager.getManager().customToast(FragmentUU.this.getContext(), "享聊-身边的心情陪伴", msg);
                        }
                    }
                });

                MobclickAgent.onEvent(FragmentUU.this.getContext(),"xiangLiao");
                break;

            case R.id.room_main_rl:
                Intent in = new Intent(getContext(), LoadCycleWebHtmlActivity.class);
                in.putExtra(BaseConfig.PUB_TYPE, 2);
                in.putExtra(BaseConfig.URL_TITLE, "会场");
                in.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL+"/events");
                startActivity(in);

                MobclickAgent.onEvent(getContext(),"huiChang");
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
